import * as echarts from 'echarts'

export function useECharts(chartRef) {
  let chartInstance: echarts.ECharts | null = null

  const initChart = () => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value)
      window.addEventListener('resize', resizeChart)
    }
  }

  const setOptions = (options: echarts.EChartsOption) => {
    if (!chartInstance) {
      initChart()
    }
    chartInstance?.setOption(options)
  }

  const resizeChart = () => {
    chartInstance?.resize()
  }

  const disposeChart = () => {
    if (chartInstance) {
      window.removeEventListener('resize', resizeChart)
      chartInstance.dispose()
      chartInstance = null
    }
  }

  return {
    setOptions,
    resizeChart,
    disposeChart,
  }
}
